#!/bin/bash
### BEGIN INIT INFO
# Provides:		telemetry
# Default-Start:	2 3 4 5
# Default-Stop:		0 1 6
# Short-Description:	telemetry - Rancher Telemetry server
# Description:		telemetry - Rancher Telemetry server
### END INIT INFO

PATH=/usr/local/sbin:/usr/local/bin:/sbin:/bin:/usr/sbin:/usr/bin
CATTLE_HOME=${CATTLE_HOME:-/var/lib/cattle}
export PIDFILE=/var/run/telemetry.pid
RUNDIR=$CATTLE_HOME
DAEMON=$RUNDIR/bin/telemetry
RUNNING_DAEMON=$CATTLE_HOME/bin/telemetry
DAEMON_ARGS="-log /var/log/telemetry.log -pid-file ${PIDFILE}"
NAME=telemetry
DESC=telemetry

if [ ! -x $DAEMON ]; then
    chmod +x $DAEMON
fi

test -x $DAEMON || exit 0

if [ -r /etc/default/$NAME ]
then
	. /etc/default/$NAME
fi

. /lib/lsb/init-functions

set -e

case "$1" in
  start)
	log_daemon_msg "Starting $DESC configuration" "$NAME" || true
	mkdir -p $RUNDIR

	if start-stop-daemon --start -b --quiet -d $RUNDIR --pidfile $PIDFILE --exec $DAEMON -- $DAEMON_ARGS
	then
	    log_end_msg 0 || true
	else
	    log_end_msg 1 || true
	fi
	;;
  stop)
	log_daemon_msg "Stopping $DESC configuration" "$NAME" || true
	if start-stop-daemon --stop --quiet --oknodo --pidfile $PIDFILE --exec $RUNNING_DAEMON
	then
	    log_end_msg 0 || true
	else
	    log_end_msg 1 || true
	fi
	rm -f $PIDFILE
	;;

  restart|force-reload)
	${0} stop
	${0} start
	;;

  reload|force-reload)
	log_daemon_msg "Reloading $DESC configuration" "$NAME" || true
	if start-stop-daemon --stop --signal 1 --quiet --oknodo --pidfile $PIDFILE --exec $RUNNING_DAEMON; then
	    log_end_msg 0 || true
	else
	    log_end_msg 1 || true
	fi
	;;

  status)
    status_of_proc -p $PIDFILE $DAEMON $NAME && exit 0 || exit $?
    ;;

  *)
	echo "Usage: /etc/init.d/$NAME {start|stop|restart|force-reload|status}" >&2
	exit 1
	;;
esac

exit 0
